import { onMounted, onUnmounted, ref } from 'vue'
import { throttle } from 'underscore'

// 监听window的滚动
export default function useScroll(elRef) {
    let el = window
    const isReachBottom = ref(false)

    const clientHeight =ref(0)
    const scrollTop =ref(0)
    const scrollHeight = ref(0)
    const scrollListHandler = throttle(() => {
        if (el === window) {
            clientHeight.value = document.documentElement.clientHeight
            scrollTop.value = document.documentElement.scrollTop
            scrollHeight.value = document.documentElement.scrollHeight
        } else {
            clientHeight.value = el.clientHeight
            scrollTop.value = el.scrollTop
            scrollHeight.value = el.scrollHeight
           
            
        }
        if (clientHeight.value + scrollTop.value >= scrollHeight.value) {
           isReachBottom.value = true
        }
    }, 100)
    onMounted(() => {
        if (elRef) {
            el = elRef.value
        }
        el.addEventListener("scroll", scrollListHandler)
    })

    onUnmounted(() => {
        el.removeEventListener('scroll', scrollListHandler)
    })

    return { isReachBottom, clientHeight, scrollTop, scrollHeight}
}